import React, { useEffect, useRef, useState } from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Divider, Button, FormInstance, DatePicker, Popconfirm, Tooltip, Form, InputNumber, Input, Row, Col } from 'antd';
import { DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getServiceRecordList, getWorkerSum, downServiceRecordList, batchStatus, getWorkerInfo } from '@/services/human-resources/api';
import { updateService, updateWorkerOrderStatus } from '@/services/order/api';
import { PageContainer } from '@ant-design/pro-layout';
import PayRecord from './PayRecord';
import { EditableProTable, ProColumns, ActionType } from '@ant-design/pro-table';
import {
  currentDate,
  formatDate,
  getDateValue,
  isExits,
  MsgType,
  parseDate2,
  showMsg,
  subtractDays,
  getjobStatus,
  isNull,
  diffDays,
  isScroll
} from '@/utils/utils';
import './style.less';
import { ProFormFieldSet, ProFormSelect, ProFormDateTimePicker } from '@ant-design/pro-form';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import { history } from 'umi';
import moment from 'moment';

interface ServiceRecordProps {
  location?: any;
}
const ServiceRecord: React.FC<ServiceRecordProps> = ({ location }) => {
  const { query } = location;
  const { worker_id, worker_name, worker_no } = query;
  const formRef = useRef<FormInstance>();
  const [form] = Form.useForm();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();

  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [downloadFlag, setDownloadFlag] = useState<boolean>(false);
  const[selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [curHg, setCurHg] = useState({});
  const [isUpdate, setIsUpdate] = useState(false); // 是否编辑
  const [curStatus, setCurStatus] = useState(''); // 当前状态
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [waitMoney, setWaitMoney] = useState(0);
  const [updateRow, setUpdateRow] = useState('');
  const [payIsEdit, setPayIsEdit] = useState(false); // 是否正在缴费
  const settRef = useRef(); // 获取结算信息的实例

  // const jobstatus = {
  //   Y: '在职',
  //   N: '离职',
  //   W: '待岗',
  // };
  const job_status = [
    {
      label: '在职',
      value: 'Y'
    },
    {
      label: '待岗',
      value: 'W'
    },
    {
      label: '离职',
      value: 'N'
    }
  ]

  const getInfo = () => {
    getWorkerInfo(worker_id).then(res => {
      setCurHg(res);
      setCurStatus(res.job_status);
    });
  }

  /**
   * 更改订单状态
   * @param record
   */
   const updateOrderStatus = async (record, status: string) => {
    try {
      const params = {
        order_id: record.order_id as string,
        status,
      };
      await updateWorkerOrderStatus(params, '300300015');
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };


  const columns: ProColumns<any>[] = [
    {
      title: '服务开始时间',
      dataIndex: 'date',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormFieldSet>
            <DatePicker style={{ width: '100%' }} />
            <span style={{ padding: '0 5px' }}>-</span>
            <DatePicker style={{ width: '100%' }} />
          </ProFormFieldSet>
        );
      },
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      className: 'wordbreak',
      width: 60,
      editable: false,
    },
    {
      title: '住院号/身份证号',
      dataIndex: 'identity_no',
      search: false,
      className: 'wordbreak',
      width: 150,
      editable: false,
      renderText: (_, record) => {
        return record.identity_no || record.admission_num;
      },
    },
    {
      title: '服务开始时间',
      dataIndex: 'begin_time',
      search: false,
      width: isScroll ? 90 : 140,
      editable: false,
    },
    {
      title: '服务结束时间',
      dataIndex: 'end_time',
      search: false,
      width: updateRow ? 150 : isScroll ? 90 : 140,
      valueType: 'dateTime',
      fieldProps: (form, record) => {
        return {
          showTime: { defaultValue: moment('23', 'HH:mm')},
          format: "YYYY-MM-DD HH:mm",
          // onOk: (val) => {
          //   const d = diffDays(moment(record.entry.begin_time), val);
          //   if (d >= 0) {
          //     const item: SettleItem = form.getFieldsValue()[record.rowKey as string];
          //     item.check_day = d.toFixed(2);
          //     form.setFieldsValue({ [record.rowKey || '']: item });
          //   } else {
          //     // showMsg('结束时间不能早于开始时间，请重新选择');
          //     // form.resetFields();
          //   }
          // },
          onChange:(val1, val) => {
            console.log('val', val, val1)
            const d = diffDays(moment(record.entry.begin_time), val);
            if (d >= 0) {
              const item: SettleItem = form.getFieldsValue()[record.rowKey as string];
              item.check_day = d.toFixed(2);
              form.setFieldsValue({ [record.rowKey || '']: item });
            } else {
              // showMsg('结束时间不能早于开始时间，请重新选择');
              // form.resetFields();
            }
          },
        };
      },
      formItemProps: (form, record) => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项',
            },
            {
              validator: (_, value) => {
                console.log('validator', moment(value).format('YYYYMMDD HHmmss'), record.entry.begin_time);
                const d = diffDays(moment(record.entry.begin_time), value);
                if (d < 0) {
                  return Promise.reject(new Error('不能为0'));
                }
                return Promise.resolve();
              },
              message: '服务结束时间不能早于开始时间',
            },
          ],
        }
      },
      render: (val, record) => {
        return record.service_id === updateRow ?
        <ProFormDateTimePicker
          width="sm"
          name="end_time1"
          // // initialValue={null}
          // initialValue={record.is_check === 'Y' ? moment(record.end_time) : []}
        />
         : record.is_check === 'Y' ? record.end_time : '-'
      }
    },
    {
      title: '服务天数',
      dataIndex: 'check_day',
      search: false,
      align: 'right',
      width: 90,
      valueType: 'digit',
      fieldProps: (form, record) => {
        return {
          // min: 0,
          precision: 2,
          style: {
            width: '100%'
          },
        }
      },
      formItemProps: (form, record) => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项',
            },
            // {
            //   validator: (_, value) => {
            //     console.log('aaaaaaa', value, parseFloat(value) < 0)
            //     if (parseFloat(value) < 0) {
            //       return Promise.reject(new Error('不能为0'));
            //     }
            //     return Promise.resolve();
            //   },
            //   message: '服务天数不能小于0',
            // },
          ],
          onChange: (e) => {
            console.log('onchange', e.target.value)
            const d = parseFloat(parseFloat(e.target.value).toFixed(2));
            if (Number.isFinite(d) && d >= 0) {
              const element = dataSource[record.rowIndex];
              element.check_total_price = parseFloat(
                parseFloat(record.entry.service_price || 0) * d,
              ).toFixed(2);
              element.check_total_recom_price = parseFloat(
                parseFloat(record.entry.recom_price || 0) * d,
              ).toFixed(2);
              element.check_day = parseFloat(d).toFixed(2);
              dataSource[record.rowIndex] = { ...element,  }
              console.log('dataSource', dataSource);
              setDataSource(Object.assign([], dataSource));
            }
          },
          onBlur: (e) => {
            const d = parseFloat(parseFloat(e.target.value).toFixed(2));
            console.log('d', d)
            if (Number.isFinite(d) && d >= 0) {
              const element = dataSource[record.rowIndex];
              element.check_total_price = parseFloat(
                parseFloat(record.entry.service_price || 0) * d,
              ).toFixed(2);
              element.check_total_recom_price = parseFloat(
                parseFloat(record.entry.recom_price || 0) * d,
              ).toFixed(2);
              element.check_day = parseFloat(d).toFixed(2);
              dataSource[record.rowIndex] = { ...element,  }
              console.log('dataSource', dataSource);
              setDataSource(Object.assign([], dataSource));
          }
        }
      }
      },
      render: (val, entity) => {
        return entity.is_check === 'Y' ? `${entity.check_day || entity.day}(${entity.is_check === 'Y' ? '已核定' : '未核定'})` : '-'
      }
    },
    {
      title: '服务收费',
      dataIndex: 'check_total_price',
      search: false,
      valueType: 'money',
      align: 'right',
      width: 90,
      editable: false,
    },
    {
      title: '介绍费',
      dataIndex: 'check_total_recom_price',
      search: false,
      valueType: 'money',
      align: 'right',
      width: 60,
      editable: false,
    },
    {
      title: '缴费单号',
      dataIndex: 'pay_id',
      search: false,
      width: isScroll ? 60 : 90,
      editable: false,
    },
    {
      title: '服务方式',
      dataIndex: 'service_type',
      search: false,
      width: 60,
      valueType: 'select',
      valueEnum: {
        I: '院内服务',
        O: '上门服务',
      },
      editable: false,
    },
    {
      title: '服务地址',
      dataIndex: 'address',
      search: false,
      editable: false,
    },
    {
      title: '缴费状态',
      dataIndex: 'recom_pay_flag',
      search: false,
      editable: false,
      width: 60,
      fixed: 'right',
      render: val => val === 'Y' ? '已缴费' : '未缴费'
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      width: isScroll ? 80 : 110,
      valueType: 'option',
      fixed: 'right',
      hideInTable: !isExits('300300012'),
      render: (_, record) => <div>{!(record.recom_pay_flag === 'Y' || payIsEdit) && <a onClick={() => {
        setUpdateRow(record.service_id);
        setSelectedRowKeys([]);
        actionRef.current?.clearSelected?.();
        actionRef.current?.startEditable(record.service_id as string);
      }}>核定</a>}
      {isExits('300300014') && <a onClick={() => history.push({ pathname: '/order/worker/patient/archiveInfo', query: { order_id: record.order_id, actId: '300300014' }  })} style={{ marginLeft: (isScroll || (record.recom_pay_flag === 'Y' || payIsEdit)) ? 0 : 10, display: isScroll ? 'block' : '' }}>档案</a>}
      {(isExits('300300015') && record.order_status === 'P') &&
        <Popconfirm
          placement="topRight"
          key="settle"
          onConfirm={async () => {
            setLoading(true);
            const success = await updateOrderStatus(record, 'F');
            if (success) {
              showMsg('已结单', MsgType.SUCCESS);
              actionRef.current?.reload();
            }
            setLoading(false);
          }}
          title="结单后，该患者档案记录将无法修改及新增预约，是否继续？"
          okText="确认结单"
          cancelText="再想想"
        >
          <a style={{ marginLeft: isScroll ? 0 : 10, display: isScroll ? 'block' : '' }}>结单</a>
        </Popconfirm>
      }

      </div>
    },
  ];

  // 汇总数据
  const [sum, setSum] = useState<HUMANRESOURCESAPI.WorkerSum>({
    total: 0,
    total_pay_price: 0,
    total_recom_price: 0,
    total_service_price: 0,
    min_begin_date: '',
    max_begin_date: '',
  });

  // 导出 TODO
  const onExport = () => {
    console.log(123);
  };

  const init = () => {
    if (worker_id) {
      getWorkerSum(worker_id).then((data: HUMANRESOURCESAPI.WorkerSum) => {
        setSum(Object.assign({}, data));
        formRef.current?.setFieldsValue({
          date: [
            data.min_begin_date ? parseDate2(data.min_begin_date) : subtractDays(30),
            '',
            data.max_begin_date ? parseDate2(data.max_begin_date) : currentDate(),
          ],
        });
        formRef.current?.submit();
        setIsUpdate(false);
      });
    }
  }
  useEffect(() => {
    getInfo();
    init();
  }, [worker_id]);

  useEffect(() => {
    // formRef.current?.setFieldsValue({
    //   date: [subtractDays(30), '', currentDate()]
    // });
    // formRef.current?.submit();
  }, []);

  // 导出缴费记录
  const download = async() => {
    setLoading(true);
    await downServiceRecordList(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  // 批量改状态
  const onBatchStatus = () => {
    if (isUpdate) {
      setLoading(true);
      batchStatus({ worker_ids: [worker_id], job_status: curStatus }).then(res => {
        setLoading(false);
        showMsg(`已修改为“${getjobStatus[curStatus]}”`, 'success');
        getInfo();
        init();
      }).catch = (error) => {
        setLoading(false);
        showMsg(error?.data?.errmsg);
      }
    } else {
      setIsUpdate(!isUpdate)
    }
  }

  console.log('waitMoney', waitMoney, sum)

  return (
    <PageContainer
      title={'服务记录'}
      extra={[<BreadcrumbDept />]}
      className="service-record-container"
      breadcrumb={{}}
      onBack={() => history.goBack()}
    >
      <div className="service-record">
        <div>
          <div className="header">
            <div className="title">1.护工信息</div>
          </div>
          <Divider style={{ margin: '10px 0' }} />
          <Row gutter={16} className="humanDes">
            <Col span={3}>工号：{curHg.worker_no}</Col>
            <Col span={3}>姓名：{curHg.worker_name}</Col>
            <Col span={5}>身份证号：{curHg.id_no}</Col>
            <Col span={4}>联系电话：{curHg.mobile}</Col>
            <Col span={4} className='myselect'>
              在职状态：
              <ProFormSelect
                readonly={!isUpdate}
                name="job_status"
                options={job_status}
                allowClear={false}
                fieldProps={{
                  value: curStatus,
                  onChange: (e) => setCurStatus(e),
                }}
              />
            </Col>
            <Col span={2}>
              <Button
                type="primary"
                onClick={() => onBatchStatus()}
                loading={isUpdate ? loading : false}
                style={{ marginTop: -2 }}
              >
                {isUpdate ? (
                  '保存'
                ) : (
                  <span>
                    切换状态
                    <Tooltip
                      title={
                        <div style={{ display: 'flex', alignItems: 'inherit' }}>
                          <ExclamationCircleOutlined style={{ margin: '2px 4px' }} />
                          <div style={{ fontSize: 12 }}>
                            <div>在职状态，护工可正常登记服务单，</div>
                            <div>待岗和离职状态，无法登记服务单。</div>
                          </div>
                        </div>
                      }
                    >
                      <QuestionCircleOutlined style={{ marginLeft: 5 }} />
                    </Tooltip>
                  </span>
                )}
              </Button>
            </Col>
          </Row>
        </div>
        <div className="header">
          <div className="title">2.服务记录</div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ marginRight: 40 }}>
              服务单数：<span style={{ color: '#F5232D', fontWeight: 'bold' }}>{sum.total}</span>
            </div>
            <div style={{ marginRight: 40 }}>
              订单总额：
              <span style={{ color: '#F5232D', fontWeight: 'bold' }}>
                {sum.total_service_price}
              </span>
              元
            </div>
            <div style={{ marginRight: 40 }}>
              介绍费：
              <span style={{ color: '#52C41A', fontWeight: 'bold' }}>{sum.total_recom_price}</span>
              元
            </div>
            <div>
              劳务费：
              <span style={{ color: '#FAAD15', fontWeight: 'bold' }}>
                {Number(sum.total_service_price - sum.total_recom_price).toFixed(2)}
              </span>
              元
            </div>
          </div>
        </div>

        <Divider style={{ margin: '10px 0' }} />

        <EditableProTable<
          HUMANRESOURCESAPI.WorkerItem,
          COMMON.PageParams & { date?: Array<string>; begin_date?: string; end_date?: string }
        >
          formRef={formRef}
          rowKey="service_id"
          className="humantable"
          manualRequest={true}
          actionRef={actionRef}
          loading={loading}
          search={{
            span: 8,
            optionRender: () => {
              return [
                <PermissionControl action_id="300300005">
                  <Button
                    key="export"
                    type="primary"
                    loading={loading}
                    disabled={!downloadFlag}
                    onClick={download}
                    icon={<DownloadOutlined />}
                  >
                    导出查询结果
                  </Button>
                </PermissionControl>,
                <Button
                  key="query"
                  type="primary"
                  onClick={() => {
                    formRef.current?.submit();
                  }}
                >
                  查询
                </Button>,
              ];
            },
          }}
          request={async (params) => {
            // console.log(params);
            try {
              params = Object.assign({}, params, { worker_id });
              let { date } = params;
              if (date) {
                params.begin_date = date[0] && formatDate(date[0], 'YYYYMMDD');
                params.end_date = date[2] && formatDate(date[2], 'YYYYMMDD');
                delete params.date;
              }

              if (date && date[0] && date[2]) {
                if (getDateValue(date[0]) > getDateValue(date[2])) {
                  showMsg('服务结束时间不能早于开始时间', MsgType.INFO);
                  return {
                    data: [],
                    total: 0,
                    success: true,
                  };
                }
              }

              for (const prop in params) {
                if (!params[prop]) {
                  delete params[prop];
                }
              }
              setSearchParams(params);
              const data: HUMANRESOURCESAPI.WorkerItemList = await getServiceRecordList(params);
              (data.record_list || []).forEach(element => {
                if (element.is_check !== 'Y') {
                  element.end_time = null;
                  element.check_day = null;
                  element.check_total_price = null;
                  element.check_total_recom_price = null;
                } 
              });
              setDownloadFlag(data.record_list.length > 0);
              setDataSource(data.record_list);
              return {
                data: data.record_list,
                total: data.sum_record_num,
                success: true,
              };
            } catch (error) {
              showMsg(error?.data?.errmsg);
              return {
                data: [],
                total: 0,
                success: true,
              };
            }
          }}
          onValuesChange={(values, record) => {
            console.log('onValuesChange', values, record, updateRow);
            if (record) {
              if (!isNull(record.end_time)) {
                dataSource.forEach((element) => {
                  if (element.service_id === record.service_id) {
                    let d = diffDays(moment(record.begin_time), moment(record.end_time));
                    d = parseFloat(d.toFixed(2))
                    console.log('d', d);
                    element.check_total_price = parseFloat(
                      parseFloat(record.service_price || 0) * d,
                    ).toFixed(2);
                    element.check_total_recom_price = parseFloat(
                      parseFloat(record.recom_price || 0) * d,
                    ).toFixed(2);
                    element.check_day = d.toFixed(2);
                  }
                });
                console.log('dataSource', dataSource);
                setDataSource(Object.assign([], dataSource));
              }
            }
          }}
          value={dataSource}
          dataSource={dataSource}
          editable={{
            form,
            type: 'single',
            editableKeys,
            onChange: setEditableRowKeys,
            onSave: async (key, row) => {
              try {
                console.log('onSave', row);
                const params = {
                  ...curHg,
                  ...row,
                  begin_time: moment(row.begin_time).format('YYYYMMDDHHmmss'),
                  end_time: moment(row.end_time).format('YYYYMMDDHHmmss'),
                };
                console.log('params', params);
                await updateService(params, '300300012');
                actionRef.current?.reload();
                setUpdateRow('');
                settRef?.current?.init();
                init();
                return true;
              } catch (error) {
                showMsg(error?.data?.errmsg);
                actionRef.current?.reload();
                setUpdateRow('');
                return false;
              }
            },
            actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],
            onCancel: async () => {
              console.log('form', form)
              form.resetFields();
              actionRef.current?.reload();
              setUpdateRow('');
            },
          }}
          columns={columns}
          recordCreatorProps={false}
          pagination={{}}
          bordered
          rowSelection={{
            columnWidth: 30,
            selections: false,
            onChange: (sel, selRow) => {
              let price = 0;
              (selRow || []).forEach((element) => {
                price += parseFloat(element.total_recom_price);
              });
              setWaitMoney(price.toFixed(2));
              setSelectedRowKeys(sel);
            },
            getCheckboxProps: (record) => {
              return {
                disabled: record.recom_pay_flag === 'Y' || record.is_check !== 'Y' || payIsEdit || updateRow,
              };
            },
          }}
          onRow={(record) => {
            return {
              onClick: (event) => {
                setClickRow(record.service_id);
              }, // 点击行
              onMouseEnter: (event) => {}, // 鼠标移入行
              onMouseLeave: (event) => {},
            };
          }}
          rowClassName={(record) => {
            return record.service_id === clickRow ? 'tableRowClick' : '';
          }}
        />
      </div>

      <PayRecord
        ref={settRef}
        worker_id={worker_id}
        selectedOrder={selectedRowKeys}
        totalMoney={waitMoney}
        onFinish={() => {
          actionRef.current?.reload();
          setSelectedRowKeys([]);
          actionRef.current?.clearSelected?.();
        }}
        onLoad={() => actionRef.current?.reload()}
        isEdit={setPayIsEdit}
      />
    </PageContainer>
  );
};

export default ServiceRecord;
